package cn.sjtu.service.impl;

import cn.sjtu.entity.User;
import cn.sjtu.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author syo 2319615164@qq.com
 * @description UserDetailsServiceImpl
 * @date 2024/10/5
 * @Copyright syo
 */
@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1. 查询用户
        User user = userMapper.selectUserByUsername(username);

        // 2. 如果没有查询到则返回空
        if (user == null) {
            return null;
        }

        // 3. 查询用户权限
        List<String> perms = userMapper.selectUserPerm(user.getId());

        // 4. 查询用户的角色
        String[] roles = userMapper.selectUserRole(user.getId()).toArray(new String[0]);

        // 5. 创建权限集合
        ArrayList<SimpleGrantedAuthority> permList = new ArrayList<>();

        for (String perm : perms) {
            permList.add(new SimpleGrantedAuthority(perm));
        }

        for (String role : roles) {
            permList.add(new SimpleGrantedAuthority("ROLE_" + role));
        }

        // 6. 创建UserDetails准备返回
        UserDetails userDetails = org.springframework.security.core.userdetails.User
                .withUsername(user.getUsername())
                .password(user.getPassword())
                .authorities(permList).build();
        return userDetails;
    }
}
